package com.example.studyllm.utils;

import cn.hutool.core.util.ReflectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.studyllm.vo.base.PageResultVO;
import lombok.experimental.UtilityClass;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * bean copy
 * @author kw
 *
 */
@UtilityClass
public class BeanUtils {
	
	/**
	 * mybatis plus page转换
	 * @param <T>
	 * @param <O>
	 * @param target
	 * @param source
	 * @return
	 */
	public  static <T, O> PageResultVO<T> changePage(Class<T> target , Page<O> source){
		PageResultVO<T> pr = new PageResultVO<>();
		List<O> oList = source.getRecords();
		List<T> tList = copyListProperties(oList, target);
		pr.setCurrent(source.getCurrent());
		pr.setTotal(source.getTotal());
		pr.setSize(source.getSize());
		pr.setMaxLimit(source.maxLimit());
		pr.setRecords(tList);
		return pr;
	}
	/**
     * 列表对象拷贝
     * @param sources 源列表
     * @param clazz 目标列表对象Class
     * @param <T> 目标列表对象类型
     * @param <M> 源列表对象类型
     * @return 目标列表
     */
    public static <T, M> List<T> copyListProperties(List<M> sources, Class<T> clazz) {
        if (Objects.isNull(sources) || Objects.isNull(clazz) || sources.isEmpty()) {
			new ArrayList<>();
        }
        List<T> targets = new ArrayList<>(sources.size());
        for (M source : sources) {
            T t = ReflectUtil.newInstance(clazz);
			POJOConverter.copy(source,t);
            targets.add(t);
        }
        return targets;
    }
    
    /**
     * 对象拷贝
     * @param <T>
     * @param <M>
     * @param source
     * @param target
     * @return
     */
    public static <T,M> T copyBean(M source , T target){
    	if (Objects.isNull(source)) {
            throw new IllegalArgumentException();
        }
		POJOConverter.copy(source,target);
    	return target;
    }
}
